package com.tqjc.system.core.pipeline;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tqjc.system.common.entity.VO.BasicResultVO;
import com.tqjc.system.common.enums.pipeline.RespStatusEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

/**
 * @author 86195
 * @version 1.0
 * @description 过程处理机
 * @date 2023/10/17 8:53
 */
@Data
@Slf4j
public class ProcessMachine {


    private Map<String,ProcessTemplate> configMap;


    public ProcessContext process(ProcessContext context) {

        //1.检查上下文
        preCheck(context);

        //2.获取责任链，调用服务器处理逻辑
        //2.1 获取责任链模板
        ProcessTemplate processTemplate = configMap.get(context.getCode());

        //2.2 获取责任链服务集合
        List<BusinessProcess> processList = processTemplate.getProcessList();
        for (BusinessProcess businessProcess : processList) {
            businessProcess.process(context);
            if (context.getBreakFlag()) {
                break;
            }
        }
        return context;
    }

    private void preCheck(ProcessContext context) {
        if(context == null){
            log.error("责任链前置检验失败,上下文对象不能为空");
            context =  new ProcessContext();
            context.setResponse(BasicResultVO.fail(RespStatusEnum.CONTEXT_IS_NULL));
        }
        //责任链责任编码
        String code = context.getCode();
        if(StrUtil.isBlank(code)){
            log.error("责任链前置检验失败,责任链编码不能为空");
            context.setResponse(BasicResultVO.fail(RespStatusEnum.BUSINESS_CODE_IS_NULL));
        }

        //检查责任表模板
        ProcessTemplate processTemplate = configMap.get(code);
        if(processTemplate == null){
            log.error("责任链前置检验失败,责任链模板配置不能为空");
            context.setResponse(BasicResultVO.fail(RespStatusEnum.PROCESS_TEMPLATE_IS_NULL));

        }

        List<BusinessProcess> processList = processTemplate.getProcessList();
        if(CollUtil.isEmpty(processList)){
            log.error("责任链前置简要失败，责任链配置不能为空");
            context.setResponse(BasicResultVO.fail(RespStatusEnum.PROCESS_LIST_IS_NULL));
        }

    }
}
